<template>
  <div class="statistics-dashboard">
    <!-- 实时统计仪表盘 -->
    <div class="dashboard-section">
      <h2>实时统计仪表盘</h2>
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-icon">📊</div>
          <div class="stat-content">
            <h3>{{ dashboardStats.totalTickets }}</h3>
            <p>总工单数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">🔓</div>
          <div class="stat-content">
            <h3>{{ dashboardStats.openTickets }}</h3>
            <p>开放工单</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">⚡</div>
          <div class="stat-content">
            <h3>{{ dashboardStats.inProgressTickets }}</h3>
            <p>处理中</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">✅</div>
          <div class="stat-content">
            <h3>{{ dashboardStats.resolvedTickets }}</h3>
            <p>已解决</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">🔒</div>
          <div class="stat-content">
            <h3>{{ dashboardStats.closedTickets }}</h3>
            <p>已关闭</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon">⏰</div>
          <div class="stat-content">
            <h3>{{ dashboardStats.overdueTickets }}</h3>
            <p>超时工单</p>
          </div>
        </div>
      </div>

      <!-- 分布图表 -->
      <div class="charts-row">
        <div class="chart-container">
          <h4>状态分布</h4>
          <div class="pie-chart" ref="statusChart"></div>
        </div>
        <div class="chart-container">
          <h4>优先级分布</h4>
          <div class="pie-chart" ref="priorityChart"></div>
        </div>
        <div class="chart-container">
          <h4>来源分布</h4>
          <div class="pie-chart" ref="sourceChart"></div>
        </div>
      </div>
    </div>

    <!-- 团队绩效报表 -->
    <div class="dashboard-section">
      <h2>团队绩效报表</h2>
      <div class="performance-metrics">
        <div class="metric-card">
          <h4>工单解决率</h4>
          <div class="metric-value">{{ teamPerformance.overallStats.teamSLAAchievementRate.toFixed(1) }}%</div>
          <div class="metric-target">目标: 85%</div>
        </div>
        <div class="metric-card">
          <h4>平均解决时间</h4>
          <div class="metric-value">{{ teamPerformance.overallStats.teamAvgResolutionTimeHours.toFixed(1) }}h</div>
          <div class="metric-target">目标: 24h</div>
        </div>
        <div class="metric-card">
          <h4>客户满意度</h4>
          <div class="metric-value">{{ teamPerformance.overallStats.teamAvgSatisfactionScore.toFixed(1) }}</div>
          <div class="metric-target">目标: 4.5</div>
        </div>
      </div>

      <!-- 团队成员列表 -->
      <!-- begin: remove 团队成员绩效表格 -->
      <!--
      <div class="team-members">
        <h4>团队成员绩效</h4>
        <div class="members-table">
          <table>
            <thead>
              <tr>
                <th>姓名</th>
                <th>角色</th>
                <th>总工单</th>
                <th>已解决</th>
                <th>超时</th>
                <th>平均解决时间</th>
                <th>满意度</th>
                <th>SLA达成率</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="member in teamPerformance.teamMembers" :key="member.userId">
                <td>{{ member.userName }}</td>
                <td>{{ member.userRole }}</td>
                <td>{{ member.totalTickets }}</td>
                <td>{{ member.resolvedTickets }}</td>
                <td>{{ member.overdueTickets }}</td>
                <td>{{ member.avgResolutionTimeHours.toFixed(1) }}h</td>
                <td>{{ member.avgSatisfactionScore.toFixed(1) }}</td>
                <td>{{ member.slaAchievementRate.toFixed(1) }}%</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      -->
      <!-- end: remove 团队成员绩效表格 -->
    </div>

    <!-- SLA统计报表 -->
    <div class="dashboard-section">
      <h2>SLA统计报表</h2>
      <div class="sla-metrics">
        <div class="sla-card">
          <h4>整体SLA达成率</h4>
          <div class="sla-value">{{ slaStatistics.overallSLAAchievementRate.toFixed(1) }}%</div>
        </div>
        <div class="sla-card">
          <h4>响应SLA达成率</h4>
          <div class="sla-value">{{ slaStatistics.responseSLAAchievementRate.toFixed(1) }}%</div>
        </div>
        <div class="sla-card">
          <h4>解决SLA达成率</h4>
          <div class="sla-value">{{ slaStatistics.resolutionSLAAchievementRate.toFixed(1) }}%</div>
        </div>
      </div>

      <!-- SLA趋势图表 -->
      <div class="chart-container">
        <h4>SLA趋势</h4>
        <div class="line-chart" ref="slaTrendChart"></div>
      </div>
    </div>

    <!-- 工单趋势图表 -->
    <div class="dashboard-section">
      <h2>工单趋势分析</h2>
      <div class="trend-charts">
        <div class="chart-container">
          <h4>工单数量趋势</h4>
          <div class="line-chart" ref="ticketTrendChart"></div>
        </div>
        <div class="chart-container">
          <h4>解决数量趋势</h4>
          <div class="line-chart" ref="resolutionTrendChart"></div>
        </div>
        <div class="chart-container">
          <h4>满意度趋势</h4>
          <div class="line-chart" ref="satisfactionTrendChart"></div>
        </div>
      </div>
    </div>

    <!-- 最近活动 -->
    <div class="dashboard-section">
      <h2>最近活动</h2>
      <div class="recent-activities">
        <div 
          v-for="activity in dashboardStats.recentActivities" 
          :key="activity.ticketId"
          class="activity-item"
        >
          <div class="activity-icon">📝</div>
          <div class="activity-content">
            <h5>{{ activity.description }}</h5>
            <p>{{ activity.userName }} - {{ formatDate(activity.timestamp) }}</p>
            <span class="ticket-number">{{ activity.ticketNumber }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="dashboard-actions">
      <button @click="refreshAll" class="btn-primary">刷新数据</button>
      <button @click="exportReport" class="btn-outline">导出报表</button>
      <button @click="scheduleReport" class="btn-outline">定时报表</button>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { statisticsApi } from '@/services/searchAndReportApi'

export default {
  name: 'StatisticsDashboard',
  setup() {
    const dashboardStats = ref({
      totalTickets: 0,
      openTickets: 0,
      inProgressTickets: 0,
      resolvedTickets: 0,
      closedTickets: 0,
      overdueTickets: 0,
      avgResolutionTimeHours: 0,
      avgSatisfactionScore: 0,
      priorityDistribution: {},
      statusDistribution: {},
      sourceDistribution: {},
      topPerformers: [],
      recentActivities: []
    })

    const teamPerformance = ref({
      teamMembers: [],
      overallStats: {
        totalTeamMembers: 0,
        activeTeamMembers: 0,
        totalTicketsHandled: 0,
        teamAvgResolutionTimeHours: 0,
        teamAvgSatisfactionScore: 0,
        teamSLAAchievementRate: 0
      },
      metrics: [],
      trends: []
    })

    const slaStatistics = ref({
      overallSLAAchievementRate: 0,
      responseSLAAchievementRate: 0,
      resolutionSLAAchievementRate: 0,
      slaByPriority: {},
      slaByCategory: {},
      slaByTeam: {},
      slaViolations: [],
      slaImprovements: []
    })

    const trendCharts = ref({
      ticketTrend: [],
      resolutionTrend: [],
      satisfactionTrend: [],
      slaTrend: [],
      priorityTrend: [],
      categoryTrend: []
    })

    // 加载所有统计数据
    const loadAllStatistics = async () => {
      try {
        const response = await statisticsApi.getComprehensiveReport()
        const data = response.data
        
        dashboardStats.value = data.dashboardStats
        teamPerformance.value = data.teamPerformance
        slaStatistics.value = data.slaStatistics
        trendCharts.value = data.trendCharts
        
        // 渲染图表
        await nextTick()
        renderCharts()
      } catch (error) {
        console.error('加载统计数据失败:', error)
        alert('加载统计数据失败: ' + error.message)
      }
    }

    // 渲染图表
    const renderCharts = () => {
      renderPieChart('statusChart', dashboardStats.value.statusDistribution)
      renderPieChart('priorityChart', dashboardStats.value.priorityDistribution)
      renderPieChart('sourceChart', dashboardStats.value.sourceDistribution)
      renderLineChart('ticketTrendChart', trendCharts.value.ticketTrend)
      renderLineChart('resolutionTrendChart', trendCharts.value.resolutionTrend)
      renderLineChart('satisfactionTrendChart', trendCharts.value.satisfactionTrend)
      renderLineChart('slaTrendChart', trendCharts.value.slaTrend)
    }

    // 渲染饼图
    const renderPieChart = (refName, data) => {
      const chartElement = document.querySelector(`[ref="${refName}"]`)
      if (!chartElement || !data) return

      // 简单的饼图实现（实际项目中可以使用Chart.js或ECharts）
      const total = Object.values(data).reduce((sum, value) => sum + value, 0)
      let html = '<div class="pie-chart-content">'
      
      Object.entries(data).forEach(([key, value]) => {
        const percentage = total > 0 ? (value / total * 100).toFixed(1) : 0
        html += `
          <div class="pie-item">
            <div class="pie-label">${key}</div>
            <div class="pie-value">${value} (${percentage}%)</div>
          </div>
        `
      })
      
      html += '</div>'
      chartElement.innerHTML = html
    }

    // 渲染折线图
    const renderLineChart = (refName, data) => {
      const chartElement = document.querySelector(`[ref="${refName}"]`)
      if (!chartElement || !data || data.length === 0) return

      // 简单的折线图实现
      const maxValue = Math.max(...data.map(d => d.value))
      let html = '<div class="line-chart-content">'
      
      data.forEach((point, index) => {
        const height = maxValue > 0 ? (point.value / maxValue * 100) : 0
        html += `
          <div class="line-point" style="height: ${height}%">
            <div class="point-value">${point.value}</div>
            <div class="point-label">${point.label}</div>
          </div>
        `
      })
      
      html += '</div>'
      chartElement.innerHTML = html
    }

    // 刷新所有数据
    const refreshAll = () => {
      loadAllStatistics()
    }

    // 导出报表
    const exportReport = async () => {
      try {
        const response = await statisticsApi.exportReportPdf('comprehensive')
        window.open(response.data, '_blank')
      } catch (error) {
        console.error('导出报表失败:', error)
        alert('导出报表失败: ' + error.message)
      }
    }

    // 定时报表
    const scheduleReport = () => {
      // 实现定时报表功能
      alert('定时报表功能开发中...')
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      return new Date(dateString).toLocaleString()
    }

    onMounted(() => {
      loadAllStatistics()
    })

    return {
      dashboardStats,
      teamPerformance,
      slaStatistics,
      trendCharts,
      refreshAll,
      exportReport,
      scheduleReport,
      formatDate
    }
  }
}
</script>

<style scoped>
.statistics-dashboard {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.dashboard-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.dashboard-section h2 {
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #007bff;
  padding-bottom: 10px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  font-size: 24px;
}

.stat-content h3 {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
}

.stat-content p {
  margin: 5px 0 0 0;
  opacity: 0.9;
}

.charts-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.chart-container {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.chart-container h4 {
  margin-bottom: 15px;
  color: #333;
  text-align: center;
}

.pie-chart,
.line-chart {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pie-chart-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.pie-item {
  display: flex;
  justify-content: space-between;
  padding: 5px 10px;
  background: white;
  border-radius: 4px;
}

.pie-label {
  font-weight: 500;
}

.pie-value {
  color: #666;
}

.line-chart-content {
  display: flex;
  align-items: end;
  gap: 5px;
  height: 100%;
  width: 100%;
}

.line-point {
  flex: 1;
  background: #007bff;
  border-radius: 4px 4px 0 0;
  display: flex;
  flex-direction: column;
  justify-content: end;
  align-items: center;
  padding: 5px;
  min-height: 20px;
}

.point-value {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.point-label {
  color: #666;
  font-size: 10px;
  margin-top: 5px;
}

.performance-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.metric-card {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.metric-card h4 {
  margin-bottom: 10px;
  color: #333;
}

.metric-value {
  font-size: 24px;
  font-weight: bold;
  color: #007bff;
  margin-bottom: 5px;
}

.metric-target {
  font-size: 14px;
  color: #666;
}

.members-table {
  overflow-x: auto;
}

.members-table table {
  width: 100%;
  border-collapse: collapse;
}

.members-table th,
.members-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.members-table th {
  background: #f8f9fa;
  font-weight: 500;
}

.sla-metrics {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.sla-card {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}

.sla-card h4 {
  margin-bottom: 10px;
}

.sla-value {
  font-size: 28px;
  font-weight: bold;
}

.trend-charts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.recent-activities {
  max-height: 400px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.activity-icon {
  font-size: 20px;
}

.activity-content {
  flex: 1;
}

.activity-content h5 {
  margin: 0 0 5px 0;
  color: #333;
}

.activity-content p {
  margin: 0 0 5px 0;
  color: #666;
  font-size: 14px;
}

.ticket-number {
  background: #007bff;
  color: white;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.dashboard-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 20px;
}

.btn-primary,
.btn-outline {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-outline {
  background: transparent;
  border: 1px solid #007bff;
  color: #007bff;
}

.btn-primary:hover {
  background: #0056b3;
}

.btn-outline:hover {
  background: #007bff;
  color: white;
}
</style>
